package com.liam.es.controller;

import com.liam.es.entity.mysql.MysqlBlog;
import com.liam.es.repository.es.EsBlogRepository;
import com.liam.es.repository.mysql.MysqlBlogRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.util.List;

@Controller
@Slf4j
public class IndexController {

    @Autowired
    MysqlBlogRepository blogRepository;

    @Autowired
    RestHighLevelClient elasticsearchClient;


    @RequestMapping("/")
    public String index() throws IOException {
        List<MysqlBlog> list = blogRepository.findAll();
        System.out.println(list.size());

        //创建queryBuilder, 从es字段：title,desc查询
//        QueryBuilder builder =  QueryBuilders.multiMatchQuery("三","name","desc");

        //设置需要高亮的es字段
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.field("desc");

        //设置es索引：products
        SearchRequest searchRequest = new SearchRequest("people");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(0);
        sourceBuilder.size(10);
        sourceBuilder.highlighter(highlightBuilder);
        sourceBuilder.timeout(new TimeValue(1000));
        searchRequest.source(sourceBuilder);

        //搜索
        SearchResponse response = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits searchHits = response.getHits();
        TotalHits total = searchHits.getTotalHits();

        log.info("录数:"  + total);

        return "index.html";
    }
}
